<template>
  <div class="main-content">
    <div class="row">
      <div class="col-sm-5 col-md-4">
        <div class="table-filter"
             style="overflow-y: auto;height: 450px;">
          <ul class="template-title-fls"
              style="padding: 10px 0 0 10px;">
            <li><input type="text"
                     v-model="searchDeptModel.deptName"
                     id="key"
                     class="form-control-sm"
                     style="width:100%;"
                     placeholder="" /></li>
            <li><button type="button"
                      class="btn btn-default btn-theme"
                      @click="queryDetpByDeptName()">查找</button></li>
          </ul>
          <ul id="orgTree2"
              class="ztree"></ul>
          <span id="orgTreeText"
                style="padding-left: 10px;font-weight: bolder;display: none;">无查询结果</span>
        </div>
      </div>
      <div class="col-sm-7 col-md-8">
        <form id="searchForm">
          <ul class="template-title-fls">
            <li>
              <el-input type="text"
                        v-model="searchUserModel.accountName"
                        name="accountName"
                        placeholder="姓名" />

            </li>
            <li>
              <el-input type="text"
                        v-model="searchUserModel.phone"
                        placeholder="手机号码" />
            </li>
            <li>
              <button type="button"
                      class="btn btn-default btn-theme"
                      v-on:click="loadPartnerByDept()"
                      style="height: 38px; width: 63px;">查询</button>
              <button type="button"
                      class="btn btn-default btn-theme"
                      v-on:click="saveCaseMemberInfo()"
                      style="height: 38px; width: 63px;">确定</button>
            </li>
          </ul>
        </form>
        <div class="user-container">
          <user-item ref="userItem"
                     @choose-click="chooseClick"
                     v-for="(row, index) in rows"
                     :key="'item-key' + index"
                     :user-info="row">
          </user-item>
        </div>
        <div class="table-responsive"
             v-if="false">
          <table class="table table-striped table-bordered min-width-790">
            <thead>
              <tr>
                <th width="7%">序号</th>
                <th width="10%">部门</th>
                <th width="15%">员工姓名</th>
                <th width="15%">联系电话</th>
                <th width="10%">角色</th>
                <th width="5%">状态</th>
                <th width="15%">驻守案场</th>
                <th width="28%">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, index) in rows">
                <td>{{index + 1}}</td>
                <td>{{row.dempName}}</td>
                <td>{{row.accountName}}</td>
                <td>{{row.phone}}</td>
                <td v-if="row.accountType == 0"
                    style="color: red;">超级管理员</td>
                <td v-else>{{ row.roleName }}</td>
                <td><span :class="[{stateOne: row.status==1, stateTwo: row.status==0}]">{{row.status==1?"启用":"禁用"}}</span></td>
                <td :title="row.propertyIdsCN">{{row.propertyIdsCN | substrFilter(0, 20)}}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div id="laypage_self_dept"
             v-if="false"></div>
      </div>
    </div>
  </div>
</template>

<script>
import UserItem from "./UserItem.vue";
import { Log, Utils } from "../../../js/base";
export default {
  components: {
    UserItem
  },
  props: {
    userList: {
      type: Array,
      default() {
        return [];
      }
    },
    premisesId: {
      type: String,
      default: ""
    }
  },
  computed: {
    userIdList() {
      let arr = [];
      this.userList.forEach((item) => {
        arr.push(item.partnerId);
      });
      return arr;
    }
  },
  mounted: function () {
    this.loadOrgTreeData();
    this.initData();
  },
  data() {
    return {
      loginInfo: {
        userId: window.localStorage.getItem("1_userId"),
        isLogin: window.localStorage.getItem("1_isLogin"),
        accountType: window.localStorage.getItem("1_accountType")
      },
      orgTreeData: [],
      rows: [],
      selectedUser: [],
      selectedPartner: {},
      pageInfo: {
        pageNo: 1,
        pageSize: 1000
      },
      addUserShow: false,
      addOrgShow: false,
      searchUserModel: {
        accountName: "",
        phone: "",
        accountType: ""
      },
      selfDeptInfo: {
        orgId: "",
        optType: ""
      },
      selfUserInfo: {
        partnerId: "",
        orgId: "",
        optType: ""
      },
      forbiddenOrNotInfo: {
        id: "",
        status: ""
      },
      bindPremisesInfo: {
        partnerId: "",
        partnerName: ""
      },
      acceptDept: {
        id: "",
        level: "",
        name: ""
      },
      partnerInfo: {
        id: "",
        name: ""
      },
      searchDeptModel: {
        deptName: ""
      },
      hiddenNodes: [],
      nodeList: [],
      premisesIds: [],
      resourcesList: {
        menu_0003_0001_0001: "menu_0003_0001_0001" //本部机构新增
      },
      userAuthResources: window.localStorage.getItem("userAuthResources")
    };
  },
  methods: {
    /**
     * 选中/取消选中点击事件
     * userInfo: {}, selected: false
     */
    chooseClick(userInfo = {}) {
      //
      if (userInfo.selected) {
        this.selectedUser.push(userInfo.id);
      } else {
        let index = this.selectedUser.indexOf(userInfo.id);
        if (index >= 0) {
          this.selectedUser.splice(index, 1);
        }
      }
    },
    loadOrgTreeData() {
      var _self = this;
      //ztree基础属性设置
      var setting = {
        data: {
          simpleData: {
            enable: true
          }
        },
        callback: {
          onClick: _self.zreeOnClick
        }
      };
      var body = {};
      body.params = {};
      var url = _self.utilHelper.apiUrl + "/api/getDeptTree";
      _self.$http.post(url, body).then(
        (response) => {
          var resData = response.body.resData;
          var nodesList = resData.nodesList;
          var result = resData.result;
          _self.$nextTick(() => {
            $.fn.zTree.init($("#orgTree2"), setting, nodesList);
          });
          $(".v-modal").trigger("click"); // hack 去除第二层蒙版
          _self.searchDeptModel.deptName = "";
          //机构树加载成功后,加载经纪人数据
          _self.loadPartnerByDept();
        },
        (response) => {}
      );
    },
    zreeOnClick(event, treeId, treeNode) {
      this.loadPartnerByDept();
    },
    openSelfDeptModal(optType) {
      //获取选中的树节点
      var treeObj = $.fn.zTree.getZTreeObj("orgTree2");
      var allNodes = treeObj.getNodes();
      var nodes = treeObj.getSelectedNodes();
      if (allNodes.length > 0 && nodes.length > 0) {
        //得到第一个选中的节点（此处位单节点选中，因此直接获取即可）
        var selNode = nodes[0];
        //将节点信息及操作按钮的点击事件类型向下传递给子组件
        this.selfDeptInfo.orgId = selNode.id;
        this.selfDeptInfo.optType = optType;
        $("#selfDeptModal").modal("show");
      } else {
        if (allNodes.length == 0 && optType == "A") {
          this.selfDeptInfo.orgId = 0;
          this.selfDeptInfo.optType = optType;
          $("#selfDeptModal").modal("show");
        } else {
          //未选中任何部门，提示用户选择
          layer.msg("请选择一个部门 ", {
            time: 1000
          });
        }
      }
    },
    selfDeptReturn() {
      this.loadOrgTreeData();
    },

    loadPartnerByDept(obj) {
      //根据机构信息，获取用户
      var _self = this;
      var params = {};
      if (!obj) {
        _self.pageInfo.pageNo = 1;
        _self.pageInfo.pageSize = 1000;
      }
      params["pageNo"] = _self.pageInfo.pageNo;
      params["pageSize"] = _self.pageInfo.pageSize;
      params["accountName"] = _self.searchUserModel.accountName;
      params["phone"] = _self.searchUserModel.phone;
      params["accountType"] = _self.searchUserModel.accountType;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree2");
      if (treeObj) {
        var node = treeObj.getSelectedNodes();
        if (node.length > 0) {
          var childNodes = treeObj.transformToArray(node);
          var nodes = "";
          for (var i = 0; i < childNodes.length; i++) {
            nodes += parseInt(childNodes[i].id) + ",";
          }
          params["deptIds"] = nodes.substring(0, nodes.lastIndexOf(","));
          //获取机构门店组别
          // _self.getQRCodeInfoByNode(node[0]);
        } else {
        }
      }
      var body = {};
      body.params = params;
      var url = this.utilHelper.apiUrl + "/api/getDevNewPartnerPage";
      this.$http.post(url, body).then(
        (response) => {
          var resData = response.body.resData;
          var total = resData.page.total;
          var totalPages = resData.page.totalPages;
          var current = resData.page.pageNumber;
          var rows = resData.page.rows;
          rows.selected = false;
          _self.rows = rows;
          _self.initData();
          //加载分页组件
          if (totalPages >= 0) {
            layui.laypage.render({
              elem: $("#laypage_self_dept"), //容器。值支持id名、原生dom对象，jquery对象,
              limit: _self.pageInfo.pageSize,
              curr: current,
              count: total,
              theme: "#f87242;", //皮肤
              first: "首页", //若不显示，设置false即可
              last: "尾页", //若不显示，设置false即可
              prev: "上一页", //若不显示，设置false即可
              next: "下一页", //若不显示，设置false即可
              layout: ["prev", "page", "next", "skip", "count"],
              jump: function (obj, first) {
                if (!first) {
                  _self.pageInfo.pageNo = obj.curr;
                  _self.loadPartnerByDept(true);
                }
              }
            });
          }
        },
        (response) => {
          console.log("加载会员失败");
        }
      );
    },
    openSelfUserModal(optType, partnerId) {
      //获取选中的树节点
      var treeObj = $.fn.zTree.getZTreeObj("orgTree2");
      var allNodes = treeObj.getNodes();
      var nodes = treeObj.getSelectedNodes();
      if ("A" == optType) {
        //新增需要机构节点
        if (nodes.length > 0) {
          //得到第一个选中的节点（此处位单节点选中，因此直接获取即可）
          var selNode = nodes[0];
          this.selfUserInfo.orgId = selNode.id;
          this.selfUserInfo.optType = optType;
          $("#selfUserModal").modal("show");
        } else {
          //未选中任何部门，提示用户选择
          layer.msg("请选择一个部门 ", {
            time: 1000
          });
        }
      } else if ("U" == optType || "V" == optType) {
        //修改无需机构节点，需得到会员ID
        this.selfUserInfo.partnerId = partnerId;
        this.selfUserInfo.optType = optType;
        $("#selfUserModal").modal("show");
      }
    },
    selfUserReturn() {
      this.loadPartnerByDept(true);
    },

    openBindPremisesModal(partnerId, partnerName) {
      //获取选中的树节点
      this.bindPremisesInfo.partnerId = partnerId;
      this.bindPremisesInfo.partnerName = partnerName;
      $("#bindPremisesModal").modal("show");
    },
    bindPremisesReturn() {
      this.loadPartnerByDept(true);
    },

    openChangePartnerDept(id, name) {
      var setting = {
        data: {
          simpleData: {
            enable: true
          }
        }
      };
      var _self = this;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree2");

      this.partnerInfo.id = id;
      this.partnerInfo.name = name;
      if (treeObj) {
        $.fn.zTree.init($("#partnerTree"), setting, treeObj.getNodes());
      }
      $("#changePartnerDeptModal").modal("show");
    },
    queryDetpByDeptName() {
      var _self = this;
      var node_type = "name";
      var treeObj = $.fn.zTree.getZTreeObj("orgTree2");
      var allNode = treeObj.transformToArray(treeObj.getNodes());
      treeObj.hideNodes(allNode);

      var keywords = _self.searchDeptModel.deptName;
      if (keywords == "") {
        $("#orgTreeText").hide();
        treeObj.showNodes(allNode);
        treeObj.expandAll(false);
      } else {
        //_self.nodeList = treeObj.getNodesByParamFuzzy("text", keywords, null);
        _self.nodeList = treeObj.getNodesByFilter(_self.filterFunc);
        _self.nodeList = treeObj.transformToArray(_self.nodeList);
        for (var n in _self.nodeList) {
          if (_self.nodeList.hasOwnProperty(n)) {
            _self.findParent(treeObj, _self.nodeList[n]);
          }
        }
        if (_self.nodeList.length > 0) {
          $("#orgTreeText").hide();
          treeObj.showNodes(_self.nodeList);
        } else {
          $("#orgTreeText").show();
        }
      }
    },
    filterFunc(node) {
      var _self = this;
      var keywords = _self.searchDeptModel.deptName;
      if (node.name.indexOf(keywords) != -1) return true;
      return false;
    },
    findParent(treeObj, node) {
      var _self = this;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree2");
      treeObj.expandNode(node, true, false, false);
      var pNode = node.getParentNode();
      if (pNode != null) {
        _self.nodeList.push(pNode);
        _self.findParent(treeObj, pNode);
      }
    },
    getQRCodeInfoByNode(node) {
      if (node.level == 0) {
        this.qrcodeNode.orgName = node.name;
        this.qrcodeNode.orgId = node.merchantId;

        this.qrcodeNode.storeName = "";
        this.qrcodeNode.storeId = "";
        this.qrcodeNode.groupName = "";
        this.qrcodeNode.groupId = "";
      }
      if (node.level == 1) {
        this.qrcodeNode.storeName = node.name;
        this.qrcodeNode.storeId = node.id;
        let pnode = node.getParentNode();
        if (pnode) {
          this.qrcodeNode.orgName = pnode.name;
          this.qrcodeNode.orgId = pnode.merchantId;
        }
        this.qrcodeNode.groupName = "";
        this.qrcodeNode.groupId = "";
      }
      if (node.level == 2) {
        this.qrcodeNode.groupName = node.name;
        this.qrcodeNode.groupId = node.id;
        let snode = node.getParentNode();
        if (snode) {
          this.qrcodeNode.storeName = snode.name;
          this.qrcodeNode.storeId = snode.id;
          let pnode = snode.getParentNode();
          if (pnode) {
            this.qrcodeNode.orgName = pnode.name;
            this.qrcodeNode.orgId = pnode.merchantId;
          }
        }
      }
    },
    saveCaseMemberInfo() {
      let _self = this;
      var body = {};
      var params = {};
      params.userIds = _self.selectedUser;
      params.premisesIds = [];
      params.premisesIds.push(_self.premisesId + "");
      if (!params.userIds || params.userIds.length == 0) {
        layer.msg("请选择人员", {
          time: 1500
        });
        return;
      }
      var cmList = [];
      for (var i = 0; i < params.userIds.length; i++) {
        if (cmList.indexOf(params.userIds[i]) == -1) {
          cmList.push(params.userIds[i]);
        }
      }
      console.log(params.userIds);
      params.companyUuid = sessionStorage.companyUuid;
      body.params = params;
      var url = _self.utilHelper.apiUrl + "/api/batchAddDefendForPremises";
      _self.$http.post(url, body).then(
        (response) => {
          var result = response.body.result;
          if (result == 1) {
            layer.msg("设置成功", {
              time: 1500
            });
            _self.$emit("modalClose");
          } else {
            layer.msg("系统异常，请稍后再试", {
              time: 1500
            });
            _self.$emit("modalClose");
          }
        },
        (response) => {
          _self.$emit("modalClose");
        }
      );
    },
    getSaveData() {
      const _this = this;
      let tableData = JSON.parse(JSON.stringify(_this.userList));
      //this.chooseUserVisible = false
      const userItemList = this.$refs.userItem;
      let userInfoList = [];
      if (userItemList && userItemList.length) {
        userItemList.forEach((item) => {
          if (item.selected && item.userInfo) {
            // item为vue实例，select是组件实例属性，标记是否选中
            item.userInfo.recommenderId = item.userInfo.id;
            item.userInfo.selected = item.selected;
            userInfoList.push(item.userInfo);
          } else if (!item.selected) {
            // 原有选中，但有此次取消的
            let index = tableData.findIndex(
              (i) => i.recommenderId === item.userInfo.id
            );
            if (index > -1) {
              tableData.splice(index, 1);
            }
          }
        });
        let tempList = [];
        if (tableData.length) {
          // 有值去重
          tableData = [...tableData, ...userInfoList];
          let obj = {},
            tempKey = "";
          tableData.forEach((item) => {
            tempKey = "key-" + item.recommenderId;
            if (!obj[tempKey]) {
              tempList.push(item);
              obj[tempKey] = true; // 标记该值已存在
            }
          });
        } else {
          tempList = userInfoList;
        }
        this.tableData = [...tempList];
      }
    },
    /**
     * 初始化数据，已选择的数据
     */
    initData() {
      if (
        !(
          this.rows &&
          this.rows.length &&
          this.userList &&
          this.userList.length
        )
      )
        return;
      this.rows.forEach((row) => {
        if (this.userIdList.includes(row.id)) {
          row.selected = true;
          if (!this.selectedUser.includes(row.id)) {
            this.selectedUser.push(row.id);
          }
        }
      });
    },
    resetUserItem() {
      let userList = this.$refs.userItem;
    }
  }
};
</script>
<style scoped>
.user-container {
  height: 400px;
  width: 600px;
  overflow: auto;
  text-align: left;
}
.text-align-left {
  text-align: left;
}
</style>
